package com.management.department.teacherinfosystem.Controller;

import com.management.department.teacherinfosystem.DTO.CourseHoursSubmitDTO;
import com.management.department.teacherinfosystem.DTO.CourseHoursDTO;
import com.management.department.teacherinfosystem.Entity.CourseHours;
import com.management.department.teacherinfosystem.Service.CourseHoursService;
import com.management.department.teacherinfosystem.Entity.AcademicSemesterConfig;
import com.management.department.teacherinfosystem.Repository.AcademicSemesterConfigRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/course-hours")
@CrossOrigin(origins = "*")
public class CourseHoursController {
    
    @Autowired
    private CourseHoursService courseHoursService;
    
    @Autowired
    private AcademicSemesterConfigRepository semesterConfigRepository;
    
    // 获取当前用户ID
    private Long getCurrentUserId(Authentication auth) {
        if (auth != null && auth.isAuthenticated()) {
            try {
                // 尝试从Principal中获取用户ID
                String username = auth.getName();
                System.out.println("当前登录用户名: " + username); // 添加调试日志
                if ("admin".equals(username)) {
                    return 1L;
                } else if ("t001".equals(username)) {
                    return 2L;
                } else if ("t002".equals(username)) {
                    return 3L;
                } else {
                    // 如果是其他用户名，记录日志并返回null
                    System.out.println("未知用户名: " + username);
                    return null;
                }
            } catch (Exception e) {
                System.out.println("获取用户ID失败: " + e.getMessage());
                return null;
            }
        }
        return null;
    }
    
    // 创建教学课时
    @PostMapping
    public ResponseEntity<?> createCourseHours(@RequestBody CourseHoursSubmitDTO dto) {
        try {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            Long userId = getCurrentUserId(auth);
            
            if (userId == null) {
                return ResponseEntity.badRequest().body("用户未登录");
            }
            
            if (dto.getMembers() == null || dto.getMembers().isEmpty()) {
                return ResponseEntity.badRequest().body("至少需要添加一个授课教师");
            }
            
            CourseHours courseHours = courseHoursService.createCourseHours(dto, userId);
            return ResponseEntity.ok("教学课时创建成功，ID: " + courseHours.getId());
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("创建失败: " + e.getMessage());
        }
    }
    
    // 更新教学课时
    @PutMapping("/{id}")
    public ResponseEntity<?> updateCourseHours(@PathVariable("id") Long id, @RequestBody CourseHoursSubmitDTO dto) {
        try {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            Long userId = getCurrentUserId(auth);
            
            if (userId == null) {
                return ResponseEntity.badRequest().body("用户未登录");
            }
            
            if (dto.getMembers() == null || dto.getMembers().isEmpty()) {
                return ResponseEntity.badRequest().body("至少需要添加一个授课教师");
            }
            
            CourseHours courseHours = courseHoursService.updateCourseHours(id, dto);
            return ResponseEntity.ok("教学课时更新成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("更新失败: " + e.getMessage());
        }
    }
    
    // 删除教学课时
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteCourseHours(@PathVariable("id") Long id) {
        try {
            courseHoursService.deleteCourseHours(id);
            return ResponseEntity.ok("教学课时删除成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("删除失败: " + e.getMessage());
        }
    }
    
    // 根据ID获取教学课时
    @GetMapping("/{id}")
    public ResponseEntity<?> getCourseHours(@PathVariable("id") Long id) {
        try {
            CourseHoursDTO courseHours = courseHoursService.getCourseHoursDTOById(id);
            if (courseHours == null) {
                return ResponseEntity.notFound().build();
            }
            return ResponseEntity.ok(courseHours);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取失败: " + e.getMessage());
        }
    }
    
         // 获取我的教学课时
     @GetMapping("/my")
     public ResponseEntity<?> getMyCourseHours() {
         try {
             Authentication auth = SecurityContextHolder.getContext().getAuthentication();
             Long userId = getCurrentUserId(auth);
             
             System.out.println("=== 获取我的教学课时 ===");
             System.out.println("认证信息: " + auth);
             System.out.println("用户名: " + (auth != null ? auth.getName() : "null"));
             System.out.println("用户ID: " + userId);
             
             if (userId == null) {
                 return ResponseEntity.badRequest().body("用户未登录");
             }
             
             List<CourseHoursDTO> courseHours = courseHoursService.getMyCourseHoursDTO(userId);
             System.out.println("查询结果数量: " + (courseHours != null ? courseHours.size() : "null"));
             
             return ResponseEntity.ok(courseHours);
         } catch (Exception e) {
             System.out.println("获取我的教学课时异常: " + e.getMessage());
             e.printStackTrace();
             return ResponseEntity.badRequest().body("获取失败: " + e.getMessage());
         }
     }
    
    // 获取所有教学课时（管理员用）
    @GetMapping("/all")
    public ResponseEntity<?> getAllCourseHours() {
        try {
            List<CourseHoursDTO> courseHours = courseHoursService.getAllCourseHoursDTO();
            return ResponseEntity.ok(courseHours);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取失败: " + e.getMessage());
        }
    }
    
    // 根据学年学期获取教学课时
    @GetMapping("/academic-year/{academicYear}")
    public ResponseEntity<?> getCourseHoursByAcademicYear(@PathVariable("academicYear") String academicYear) {
        try {
            List<CourseHoursDTO> courseHours = courseHoursService.getCourseHoursDTOByAcademicYear(academicYear);
            return ResponseEntity.ok(courseHours);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取失败: " + e.getMessage());
        }
    }
    
         // 根据教师姓名获取教学课时
     @GetMapping("/user/{userName}")
     public ResponseEntity<?> getCourseHoursByUserName(@PathVariable("userName") String userName) {
         try {
             List<CourseHoursDTO> courseHours = courseHoursService.getCourseHoursDTOByUserName(userName);
             return ResponseEntity.ok(courseHours);
         } catch (Exception e) {
             return ResponseEntity.badRequest().body("获取失败: " + e.getMessage());
         }
     }
     
     // 根据教师姓名和学年学期获取教学课时
     @GetMapping("/user/{userName}/academic-year/{academicYear}")
     public ResponseEntity<?> getCourseHoursByUserNameAndAcademicYear(
             @PathVariable("userName") String userName, 
             @PathVariable("academicYear") String academicYear) {
         try {
             List<CourseHoursDTO> courseHours = courseHoursService.getCourseHoursDTOByUserNameAndAcademicYear(userName, academicYear);
             return ResponseEntity.ok(courseHours);
         } catch (Exception e) {
             return ResponseEntity.badRequest().body("获取失败: " + e.getMessage());
         }
     }
    
    // 获取学年学期统计
    @GetMapping("/statistics/academic-year/{academicYear}")
    public ResponseEntity<?> getStatisticsByAcademicYear(@PathVariable("academicYear") String academicYear) {
        try {
            Double totalStandardHours = courseHoursService.getTotalStandardHoursByAcademicYear(academicYear);
            Double totalConvertedHours = courseHoursService.getTotalConvertedHoursByAcademicYear(academicYear);
            
            return ResponseEntity.ok(Map.of(
                "academicYear", academicYear,
                "totalStandardHours", totalStandardHours != null ? totalStandardHours : 0.0,
                "totalConvertedHours", totalConvertedHours != null ? totalConvertedHours : 0.0
            ));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取统计失败: " + e.getMessage());
        }
    }
    
    // 获取用户统计
    @GetMapping("/statistics/user/{userId}")
    public ResponseEntity<?> getStatisticsByUserId(@PathVariable("userId") Long userId) {
        try {
            Double totalStandardHours = courseHoursService.getTotalStandardHoursByUserId(userId);
            Double totalConvertedHours = courseHoursService.getTotalConvertedHoursByUserId(userId);
            
            return ResponseEntity.ok(Map.of(
                "userId", userId,
                "totalStandardHours", totalStandardHours != null ? totalStandardHours : 0.0,
                "totalConvertedHours", totalConvertedHours != null ? totalConvertedHours : 0.0
            ));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取统计失败: " + e.getMessage());
        }
    }
    
    // 获取教师列表（用于筛选）
    @GetMapping("/teachers")
    public ResponseEntity<?> getTeachersList() {
        try {
            List<Object> teachers = courseHoursService.getTeachersList();
            return ResponseEntity.ok(teachers);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取教师列表失败: " + e.getMessage());
        }
    }
    
    // 获取学年学期配置
    @GetMapping("/semester-config")
    public ResponseEntity<?> getSemesterConfig() {
        try {
            List<AcademicSemesterConfig> configs = semesterConfigRepository.findByIsActiveTrueOrderBySortOrderAsc();
            return ResponseEntity.ok(configs);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取学年学期配置失败: " + e.getMessage());
        }
    }
}
